package com.yc.testThread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * https://blog.csdn.net/u010452388/article/details/82777908
 * @author yuancan
 *
 */
public class TestThread3 {
	
	int index = 1;
	int currentThreadNum = 1;
	
	//使用Lock Condition实现“定向唤醒”
	Lock lock = new ReentrantLock();
	Condition[] conditionArray = {lock.newCondition(), lock.newCondition(), lock.newCondition()};

	public static void main(String[] args) {
		TestThread3 tt = new TestThread3();
		tt.m();

	}
	
	public void m() {
		new Thread(new myTask(), "1").start();
		new Thread(new myTask(), "2").start();
		new Thread(new myTask(), "3").start();
	}
	
	class myTask implements Runnable {

		@Override
		public void run() {
			Integer threadNum = Integer.parseInt(Thread.currentThread().getName());
			while(true) {
				try {
					lock.lock();
//					System.out.println("---线程"+ threadNum + "-----in");
					
					while(!threadNum.equals(currentThreadNum)) {//不该自己执行：等待（并释放锁）,jdk建议使用while
//						System.out.println("---线程"+ threadNum + "-----await");
						if (index < 100) {
							conditionArray[threadNum-1].await();
						} else {
							break;
						}
					}
					
					if (index > 99) {
//						System.out.println("---线程"+ threadNum + "唤醒所有线程");
						notifyAll1();//唤醒所有线程
						break;//结束
					}
					
					for (int i = 0; i < 3; i++) {
						System.out.println("threadName:" + Thread.currentThread().getName() + "--" + index);
						index++;
					}
					
					if (threadNum != 3) {
						currentThreadNum = threadNum+1;
					} else {
						currentThreadNum = 1;
					}
					conditionArray[currentThreadNum-1].signal();//把下一个执行的线程唤醒，让它参与争锁
//					System.out.println("---线程"+ currentThreadNum + "-----被唤醒");
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
				
			
			}//while end
			
		}
		
	}
	
	public void notifyAll1() {
		for (int i = 0; i < 3; i++) {
			conditionArray[i].signal();
		}
		
	}

}
